package xc;

public class demo2 {
    static class my_thread extends Thread{

        static int ticket=0;
        //锁对象一定要保持唯一
        static Object obj = new Object();

        public void run(){
            while(true){
                //同步代码
                synchronized (obj){
                    if(ticket<100){
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        ticket++;
                        System.out.println(getName() + "正在卖第" + ticket + "张票.");
                    }   else{
                        break;
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new my_thread();
        Thread t2 = new my_thread();
        Thread t3 = new my_thread();

        t1.setName("t1");
        t2.setName("t2");
        t3.setName("t3");

        t1.start();
        t2.start();
        t3.start();
    }

}
